package com.quan.commons.core.configuration;

import com.alibaba.fastjson.JSON;
import com.quan.commons.core.properties.SystemValueProperties;
import com.quan.commons.core.utils.JwtUtils;
import com.quan.system.commons.vo.SysUserVo;
import com.quan.system.entity.SysUser;
import com.quan.system.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 拦截器
 * 获取当前登录用户的信息保存到当前线程中，便于程序调用
 */
@Component
public class LoginUserInterceptor implements HandlerInterceptor {

    public static ThreadLocal<SysUserVo> loginUser = new ThreadLocal<>();

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SystemValueProperties properties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");

        if(null != token) {
            // 用户信息
            //SysUserVo user = this.sysUserService.getUserInfoByToken(token);

            // 解析Token数据，获取用户信息
            final String userJSON = JwtUtils.getUser(token);
            final SysUserVo user = JSON.parseObject(userJSON, SysUserVo.class);

            //把登录后用户的信息放在ThreadLocal里面进行保存
            loginUser.set(user);
        }

        return true;
    }
}
